package com.qingke.studentinfo.Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.qingke.studentinfo.pojo.Student;

public class StudentDao extends BaseDao {

	public int addStudent(Student student) {
		String sql = "insert into student(stu_name) value(?)";
		return update(sql, student.getStuName());
	}
	
	public List<Student> findAll(Student student) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Student> allStudents = new ArrayList<>();
		String sql = "select * from student where 1=1 ";
		
		if(student.getStuId() != null) {
			sql = sql + "and stu_id =" + student.getStuId() + " ";
		}
		
		if(student.getStuName() != null && !student.getStuName().equals("")) {
			sql = sql + "and stu_name= ?";
		}
		
		try {
			conn = getConnection();
			pstmt = conn.prepareStatement(sql);
			if(student.getStuName() != null && !student.getStuName().equals("")) {
				pstmt.setString(1, student.getStuName());
			}
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				Student stu = new Student();
				stu.setStuId(rs.getInt("stu_id"));
				stu.setStuName(rs.getString("stu_name"));
				allStudents.add(stu);
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			closeAll(conn, pstmt, rs);
		}
		
		return allStudents;
	}
}
